package dao

import (
	"fmt"
	"gorm.io/gorm"
	"strconv"
	"vehicle_management_srv/config"
)

// 司机表
type Driver struct {
	gorm.Model
	Username string `gorm:"type:varchar(30);not null;comment:'用户名'"`
	Password string `gorm:"type:char(32);not null;comment:'密码'"`
}

// 司机详情表
type DriverDetails struct {
	gorm.Model
	DriverId int    `gorm:"type:int(10);not null;comment:'司机ID'"`
	Mobile   string `gorm:"type:char(11);not null;comment:'手机号'"`
	RealName string `gorm:"type:varchar(50);not null;comment:'姓名'"`
}

// 车辆详情表
type VehicleDetails struct {
	gorm.Model
	VehicleName   string `gorm:"type:varchar(30);not null;comment:'车辆名称'"`
	VehicleNumber string `gorm:"type:varchar(30);not null;comment:'车牌号'"`
	Certified     int8   `gorm:"type:tinyint(1);default:0;comment:'是否认证:0-没认证,1-已认证'"`
}

// 车辆司机关联表
type VehicleAndDriver struct {
	gorm.Model
	DriverId  int `gorm:"type:int(10);not null;comment:'司机ID'"`
	VehicleId int `gorm:"type:int(10);not null;comment:'车辆ID'"`
}

func (v *VehicleDetails) VehicleCreate(driverId int64) (uint, string) {
	err := config.DB.Create(&v).Error
	if err != nil {
		return 0, "车辆详情表添加失败"
	}
	vv := VehicleAndDriver{
		DriverId:  int(driverId),
		VehicleId: int(v.ID),
	}
	err = config.DB.Create(&vv).Error
	if err != nil {
		return 0, "关联表添加失败"
	}
	return v.ID, ""
}

func (v *VehicleDetails) VehicleUpdate(vehicleId, certified int64) string {
	var vv VehicleDetails
	fmt.Println(vehicleId)
	config.DB.Where("id=?", vehicleId).First(&vv)
	err := config.DB.Model(&vv).Update("certified", certified).Error
	if err != nil {
		return "修改失败"
	}
	return ""
}

func (v *VehicleDetails) VehicleShow(vehicleId int64) (string, string) {
	var vv VehicleDetails
	config.DB.Where("id=?", vehicleId).First(&vv)
	if vv.ID == 0 {
		return "", "获取失败"
	} else {
		if vv.Certified == 0 {
			return "未认证", ""
		}
		return "已认证", ""
	}
}

func (v *VehicleDetails) VehicleSearch(name string) (VehicleDetails, string) {
	var vv VehicleDetails

	config.DB.Where("vehicle_name=?", name).First(&vv)
	if vv.ID == 0 {
		return vv, "搜索失败"
	}
	lKey := "vehicle"
	key := "vehicle" + strconv.Itoa(int(vv.ID))
	config.RDB.ZIncrBy(lKey, 1, key)
	return vv, ""
}
